<template>
  <formItem :item="item">
    <a-tree
      v-model="item['value']"
      checkable
      :auto-expand-parent="autoExpandParent"
      :tree-data="areaList"
      :disabled="disabled"
      :replaceFields="replaceFields"
      @check="onCheck"
    />
  </formItem>
</template>

<script>
export default {
  components: {
    formItem: () => import('./formItem.vue')
  },

  props: {
    disabled: {
      type: Boolean
    },

    areaList: {
      type: Array,
      default() {
        return []
      }
    },

    item: {
      type: Object,
      default() {
        return null
      }
    }
  },

  watch: {
    'item.value'(val) {
      let [max, min] = this.getAreaAttr
      if (val.length > max) {
        this.$message.error(`最多只能选择${max}条~`)
      }
    }
  },

  data() {
    return {
      autoExpandParent: true,
      replaceFields: { children: 'children', title: 'name', key: 'adcode' }
    }
  },

  computed: {
    getAreaAttr() {
      let newArr = JSON.parse(JSON.stringify(this.item.rules.rule))
      if (!Array.isArray(newArr)) {
        newArr = [newArr]
      }

      let arr = [0, 0] //  0.最大长度 1.最小长度
      newArr.forEach(el => {
        let item = el['@attributes']
        switch (item.type) {
          case 'maxSize':
            arr[0] = parseInt(item.value)
            break
          case 'minSize':
            arr[1] = parseInt(item.value)
            break
        }
      })

      return arr
    }
  }
}
</script>
